import itertools
from functools import partial

from app.common.const import MAX_PAGE_LEN_LIMIT
from app.common.errors import ApiError
from app.common.errors import Error
from promise.dataloader import DataLoader as _DataLoader


class DataLoader(_DataLoader):
    max_keys_length = MAX_PAGE_LEN_LIMIT

    def load_many(self, keys):
        if self.max_keys_length and len(set(keys)) > self.max_keys_length:
            raise ApiError(Error.CUSTOM_ERROR, err="You load too much data at once!")
        return super().load_many(keys)

    def load_many_and_filter_none(self, keys, n=None):
        promise = self.load_many(keys).then(partial(filter, None))
        if n is None:
            return promise
        else:
            return promise.then(lambda l: itertools.islice(l, n))
